package com.wzs.rpc.loadbalancer;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

@Slf4j
public class LoadBalancerFactory {
    private static final Map<String, Object> instanceCache = new HashMap<>();
    private static final LoadBalancer DEFAULT_LOAD_BALANCER = new RoundRobinLoadBalancer();

    //饿汉，加载时便初始化，避免多线程下的安全问题
    static {
        ServiceLoader<LoadBalancer> loadBalancers = ServiceLoader.load(LoadBalancer.class);
        for (LoadBalancer loadBalancer : loadBalancers) {
            instanceCache.put(loadBalancer.getClass().getName(), loadBalancer);
        }
        log.debug("SPI加载LoadBalancer, 实例个数为 {}", instanceCache.size());
    }

    public static LoadBalancer getInstance(String loadBalancer) {
        return (LoadBalancer) instanceCache.getOrDefault(loadBalancer, DEFAULT_LOAD_BALANCER);
    }
}
